package com.forum.service.rank.listener;


import com.forum.service.rank.consts.Const;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author lbwxxc
 * @date 2025/4/6 17:18
 * @description: 用于接收 rank 队列的消息
 */
@Component
@RabbitListener(queues = "rank")
@Slf4j
public class UserActivityListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitHandler
    public void notifyMsgListener(Map<String, Object> data) {
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            try {
                int count = Integer.parseInt(value.toString());
                if (redisTemplate.opsForValue().get(key) != null) {
                    log.info("存在用户试图进行违法操作");
                } else {
                    redisTemplate.opsForValue().set(Const.RANK_KEY, String.valueOf(count), Const.RANK_KEY_EXPIRE_TIME,
                                                                                           Const.RANK_KEY_EXPIRE_TIME_UNIT);
                    String[] strings = key.split(":");
                    redisTemplate.opsForZSet().incrementScore(Const.RANK_KEY, strings[strings.length - 1], count);
                }
            } catch (NumberFormatException e) {
                log.error("数据转换异常，key: {}, value: {}", key, value, e);
            } catch (Exception e) {
                log.error("Redis操作异常，key: {}, value: {}", key, value, e);
            }
        }
    }

    /**
     * @param:
     * @return: void
     * @description: 定时刷新用户活跃度排行榜
     */
    @Scheduled(cron = "0 1 10 15 * ?")
    @Async
    public void AutoRefreshRank() {
        redisTemplate.delete(Const.RANK_KEY);
    }

    /**
     * @param:
     * @return: org.springframework.core.task.AsyncTaskExecutor
     * @description: 自定义定时任务的线程池，在接口的实现类自定义线程池会报错
     */
    @Bean
    public AsyncTaskExecutor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("yhh-schedule-");
        executor.setMaxPoolSize(10);
        executor.setCorePoolSize(3);
        executor.setQueueCapacity(0);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }
}
